package com.abu.authms.controller;

import com.abu.authms.properties.JwtProperties;
import com.abu.authms.properties.DDProperties;
import com.abu.authms.service.AuthService;
import com.abu.utils.CookieUtils;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.request.AuthAlipayRequest;
import me.zhyd.oauth.request.AuthDingTalkRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@RestController
@RequestMapping("/oauth/dd")
@EnableConfigurationProperties(DDProperties.class)
public class OAuthController {

    @Autowired
    private DDProperties aliProperties;
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private AuthService authService;

    @RequestMapping("/render")
    public void renderAuth(HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    @RequestMapping("/callback")
    public String login(AuthCallback callback, HttpServletResponse response, HttpServletRequest request) {
        AuthRequest authRequest = getAuthRequest();
//        1.获取返回结果集
        AuthResponse authResponse = authRequest.login(callback);
//        2.生成token
        String token = authService.checkLogin(authResponse);
//       将token放入cookie中
        CookieUtils.setCookie(request, response, jwtProperties.getCookieName(), token, jwtProperties.getExpire() * 11);
        return "登陆成功";
    }

    @RequestMapping("/revoke/{token}")
    public Object revokeAuth(@PathVariable("token") String token) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        return authRequest.revoke(AuthToken.builder().accessToken(token).build());
    }

    private AuthRequest getAuthRequest() {
        return new AuthDingTalkRequest(AuthConfig.builder()
                .clientId(aliProperties.getClientId())
                .clientSecret(aliProperties.getClientSecret())
                .redirectUri(aliProperties.getRedirectUri())
                .build());
    }
}
